package com.example.wuyurun

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.io.*

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: StudentAdapter
    private var students: MutableList<Student> = mutableListOf()

    companion object {
        const val REQUEST_PERMISSION_CODE = 100
        const val STUDENT_FILE = "students.txt"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.title = "仵雨润2022110642" // 替换为你的姓名和学号

        recyclerView = findViewById(R.id.rv_students)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = StudentAdapter(students)
        recyclerView.adapter = adapter

        findViewById<Button>(R.id.btn_add_student).setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            startActivity(intent)
        }

        // 请求存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            requestStoragePermission()
        } else {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION_CODE)
            } else {
                loadStudents()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.R)
    private fun requestStoragePermission() {
        if (Environment.isExternalStorageManager()) {
            loadStudents()
        } else {
            val permission = Manifest.permission.WRITE_EXTERNAL_STORAGE
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(permission),
                    REQUEST_PERMISSION_CODE
                )
            } else {
                loadStudents()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadStudents()
            } else {
                Log.i("MainActivity", "Permission denied")
            }
        }
    }

    private fun loadStudents() {
        students.clear()
        try {
            val inputStream = openFileInput(STUDENT_FILE)
            val reader = BufferedReader(InputStreamReader(inputStream))
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                val data = line!!.split(",")
                students.add(Student(data[0], data[1], data[2], data[3]))
            }
            reader.close()
            inputStream.close()
        } catch (e: FileNotFoundException) {
            Log.i("MainActivity", "Students file not found, creating new one")
            try {
                val outputStream = openFileOutput(STUDENT_FILE, Context.MODE_PRIVATE)
                outputStream.close()
                Log.i("MainActivity", "Created new students file")
            } catch (ex: IOException) {
                Log.e("MainActivity", "Failed to create students file", ex)
            }
        } catch (e: IOException) {
            Log.e("MainActivity", "Error reading students file", e)
        }
        adapter.updateList(students)
        Log.d("MainActivity", "Loaded ${students.size} students")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            val studentData = data.getStringExtra("student")
            try {
                val outputStream = openFileOutput(STUDENT_FILE, Context.MODE_APPEND)
                outputStream.write("$studentData\n".toByteArray())
                outputStream.close()
            } catch (e: IOException) {
                Log.e("MainActivity", "Error writing students file", e)
            }
            loadStudents()
        }
    }
}